// 引入接口文件
import {
  getAreaList,
  getHouseList,
  getDetail,
  create,
  getDetaildatas
} from './intermediaryDetailServ'

// 对象和JSON字符串互转
import { parse } from 'qs'
// 弹出消息框
import { Modal,message } from 'antd'
const confirm = Modal.confirm;
// 日期处理对象
import moment from 'moment'
/*isEmpty 对象是否为空
 *isArray 对象是否数组
 *cloneDeep 对象深拷贝
 */
import { isEmpty, isArray, cloneDeep, merge, pick,set,get } from 'lodash'
// 引入路由对象
import { hashHistory } from 'dva/router'
import AppBus from '../../../utils/bus'
import { makeAddress } from 'utils/util'
import config from 'config/config'
let productTypeLabelMap = { 1: '详细房号', 2: '车位位置', 3: '商铺位置', }
import {reqInform, showConfirm} from 'utils/notification'
// 初始默认状态
const defultState = {
  xxx: '1',
  id: '',
  selectedKey:"",//选择的数据
  loading: false,
  btnLoading: false,
  pageType: 'detail',
  allAreaList: [],
  areaList: [],
  selectedRowKeys: [],
  biz1: {},
  
  detailInfo: {
    detailInfo:{},
    orgBasicInfo:{},
    businessInfo:{},
  },
  onItem: [],//临时放置选中项目
  // 表格数据
  tableData: {
    // dataSource: [
    //
    // ],
    dataSource: [],
    total: 0,
    stop:0,
    start:0
  },
  // 表格分页设置
  pageConfig: {
    pageSize: Number.parseInt(config.smallPageSizeList[0]),
    pageNo: 1
  },
  
  houseList: [],
  targetKeys: [],
  selectedKeys: [],
  selectedRows: [],
  projectLabels: [],
  selectedTeams: [],
  productList: [],
  
  formData: {
    newTime:null,
    state:1,//	状态（ 1、正常 2、禁用）
    coperationDate:null,
    houseList:[],
    teams:[],
    orgBasicInfo:{
      name:'',
      legalMan:'',
      orgCode:'',
      addressCode:'',
      addressCodes:'',
      detailAddress:'',
      description:'',
      fmsVendorNum: '',
      incompanyCode: ''
      // orgId:'',
    },
    businessInfo:{
      startDate:'',
      endDate:'',
      // visitMinHours:'2'
      // agentConfigId:'',//中介配置（业务信息）id,查询详情会返回，修改的时候再传回来（新增无此参数）
    },
  },
  modalObj: {
    visible: false,
    defaultReqParams: {},
    queryList: [
      { name: '省市', type: 'cascader', list: [], key: ['province', 'city']},
      {name: '楼盘名称', type: 'text', key: 'name', value: '',placeholder:'支持模糊查询'},
      ],
  },
  timeModalObj: {
    visible: false,
  },
  nameModalObj: {
    visible: false,
  },
  teamsModalObj: {
    visible: false,
  },
  visitTime:false,
  marketingAction:false
}
// 声明module
const tmpModule = {
  // namespace: 'secondKillingSetting',
  // 默认状态
  state: cloneDeep(defultState),
  // 入口函数(先执行)
  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname, query }) => {
        // 页面路由匹配时执行
        if ('' + tmpModule.pathname === '' + pathname) {
         
          query.id=query.orgId+''
          dispatch({ type: 'updateStore', payload: { ...cloneDeep(defultState), ...query } })//每次进去页面先重置状态
          console.log('subscriptions', pathname, query)
          if (query.pageType == 'edit') {
            dispatch({type: 'queryInfo',payload: {pageType: query.pageType,id: query.id, } })
          } else {
            dispatch({type: 'updateStore',payload: {pageType: query.pageType,id: query.id, } })
          }
          dispatch({type: 'getDetaildatas',payload: {} })
          dispatch({ type: 'getAreaList', payload: {} })
          dispatch({ type: 'powerInfo', payload: {} })
          
        } // end if
      }) // end listen
    },
  },
  
  // 方法列表
  effects: {
    //报备时间权限
    *powerInfo({ payload }, { put, call, select }){
      let subElements = JSON.parse(localStorage.getItem('navBar')).subElements;
      let allow1=subElements.includes(40105)
      let allow2=subElements.includes(40106)
      // console.log(allow)
      if(allow1){
        yield put({
          type: 'updateStore',
          payload: {
            visitTime:allow1
          }
        })
      }
      if(allow2){
        yield put({
          type: 'updateStore',
          payload: {
            marketingAction:allow2
          }
        })
      }
    },
    // 查询记录  详情
    * queryInfo({ payload }, { put, call, select }) {
      let { id, detailInfo, formData, tags, imageUrls,targetKeys,tableData,pageConfig,onItem } = yield select(state => state[tmpModule.namespace])
      const { success, msg, data={} } = yield call(getDetail, { id: payload.orgId || id })
      if (success) {
        let {businessInfo={},}=data
        detailInfo = data || {}
        formData = data || {}
        //已选择楼盘
        let cooperationProducts =get(data,'cooperationProducts',[])
        let teams = get(data,'teams',[])
        cooperationProducts.map((item, index) => {
          let {date=null,startDate=null,endDate=null}=item
          item.key = item.productId;
          item.name = item.projectName;
          item.disabled = true
          if(!date&&(startDate||endDate)){
            item.date=[startDate||null,endDate||null]
          }
          item['teamNames'] = ''
          // productId = item.productId;
        })
        let total=cooperationProducts.length
        onItem=cooperationProducts

        tableData = {
          dataSource: cooperationProducts,
          total: Number(total)
        }
        for(var item of tableData.dataSource){
          for(var itemed of teams){
                if(itemed.productList&&itemed.productList.length){
                  for(var it of itemed.productList){
                    if(it.productId ==item.productId){
                        item.teamNames += itemed.teamName + ","
                    }
                  }
                }
              }
          item.teamNames = item.teamNames.substring(0, item.teamNames.length - 1);
        }
      }
      yield put({
        type: 'updateStore',
        payload: {
          detailInfo,
          onItem,
          formData,
          tableData,
          targetKeys,
          ...payload,
        }
      })
    },
    
    // 获取列表编辑权限
    *getDetaildatas({ payload }, { put, call, select }) {
        let { productList} = yield select(state => state[tmpModule.namespace])
        productList = []
        let username = localStorage.getItem('username')
        if(username == 'admin'){
          return false
        }
        let navBar = JSON.parse(localStorage.getItem('navBar'))
        let params= {accountId: navBar.accountId}
        const { success, data } = yield call(getDetaildatas, params)
        if (success) {
          let products = data.products
          for(var item of products){
            productList.push(item.productId)
          }
          yield put({
            type: 'updateStore',
            payload: {
              productList
            }
          })
        }
    },
    
    // 新增 adminInfo(name preMobile)   orgBasicInfo(name legalMan  orgCode addressCode detailAddress orgId ) businessInfo(startDate endDate  commissionRate visitValidTime recommendValidTime dealValidTime  agentConfigId )  houseList  state
    * create({ payload={} }, { put, select, call }) {
      let { id, formData, tags, targetKeys, tableData} = yield select(state => state[tmpModule.namespace])
      formData=cloneDeep(formData)
      formData.teams.map((item) => {
        if(item.productList){
          var list = []
          for(var it of item.productList){
            list.push(it.productId)
          }
          item['productIds'] = list
        }else{
          item['productIds'] = []
        }
      })
      for(var itemed of formData.teams){
        for(var item of tableData.dataSource){
          if(!item.teamNames){
            message.warn('合作楼盘的团队名称不能为空，请在合作楼盘维护团队')
            return false
          }
          let arr1 = item.teamNames?item.teamNames.split(","):''
          if(arr1.includes(itemed.teamName)){
            itemed.productIds.push(item.productId)
          }
        }
        itemed.productIds = [...new Set(itemed.productIds)] 
      }

      let addressCodes=get(formData,'orgBasicInfo.addressCodes')||[]
      formData.orgBasicInfo.addressCode=addressCodes[addressCodes.length-1]
      let {dataSource=[]}=tableData
      let arr=[]
      let invalidItemArr=[]
      dataSource.map((item)=>{
        console.log(item)
        let {date=[],productId,productName,name,visitMinHours}=item
        if(!isEmpty(date)){
          let [startDate,endDate]=date
          arr.push({
            startDate:startDate,
            endDate:endDate,
            productId,
            productName:productName||name,
            visitMinHours
          })
        }else{
          invalidItemArr.push(productName||name)
        }
      })
      if(invalidItemArr.length){
        message.warn('以下项目：'+invalidItemArr.join('、')+'，请设置项目有效时间')
        return  false
      }
      let params = {
        ...pick(formData, ['teams', 'orgBasicInfo', 'businessInfo', 'state']),
        productIds:targetKeys.join(','),
        cooperationProducts:arr,
      }
      // 商品类型非房源，不用传户型和户型朝向
      yield put({ type: 'updateStore', payload: { btnLoading:true } })
      const { success, msg, data,code } = yield call(create, { ...params,...pick(payload,['type']) },false)
      yield put({ type: 'updateStore', payload: { btnLoading:false } })
      if (success) {
        message.success('操作成功', 1, () => {
          // yield put({type: 'queryInfo', payload: {}})
          let urlArray = MODULE_TO_ROUTES[tmpModule.namespace].urlArray
          console.log('urlArray', urlArray)
          AppBus.emit('closeTab', {
            key: urlArray[0],
            cbf: () => {
              hashHistory.push(urlArray[1])
            }
          })
        })
      }else if(!success&&code=='10001'){
        yield put({ type: 'updateStore', payload: { callModal:true,callModalTitle:msg } })
      }else{
        reqInform({
          title: '系统提示',
          description: msg
        }, 'warn')
      }
    },
    
    // 获取区域地址
    *getAreaList({ payload }, { put, call, select }) {
      let {modalObj,} = yield select(state => state[tmpModule.namespace])
      try {
        
        const { success, data=[] } = yield call(getAreaList)
        if (success) {
          let allAreaList=cloneDeep(data)
          let areaList=cloneDeep(data)
          let arr = [areaList[0]]
          areaList[0] = {
            label: '北京',
            value: '110100',
            children: arr
          }
          //去掉第三级，
          for (var i = 0; i < 33; i++) {
            for (var j = 0; j < areaList[i].children.length; j++) {
              delete areaList[i].children[j].children
            }
          }
          modalObj.queryList[0].list=areaList
          yield put({ type: 'updateStore', payload: { areaList,allAreaList,modalObj } })
        }
      } catch (e) {
        console.log(e)
      }
    },
    // 获取户型项目
    *getHouseList({ payload }, { put, call, select }) {
      // shelfStatus 0-未上架 1-已上架 2-已下架
      let params={ ...payload,shelfStatus:1, pageSize: 10000 }
      try {
        const { success, rows } = yield call(getHouseList, params)
        if (success) {
          let list=rows||[]
          let arr=[]
          list.map((item,index)=>{
            arr.push({ title: item.name||item.productName||'', description: item.name||item.productName||'',value: item.productId+''||'', key: item.productId+''||'' })
          })
          yield put({ type: 'updateStore', payload: { houseList: arr || [] } })
        }
      } catch (e) {
        console.log(e)
      }
    },
    * selectedKeysChange ({payload}, {put, select, call}) {
      let {modalObj,selectedRowKeys,selectedRows} = yield select(state => state[tmpModule.namespace])
      // selectedRowKeys
      console.log('selectedKeysChange',payload)
      selectedRowKeys=payload.selectedRowKeys
      selectedRows=payload.selectedRows
      yield put({
        type: 'updateStore',
        payload: {
          selectedRowKeys,selectedRows
        }
      })
    },
    
  },
  // 存入状态机
  reducers: {
    updateStore(preState, action) {
      return Object.assign({}, preState, action.payload)
    },
  }
}

export default tmpModule
